<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>测试发送短信</title>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css" />
    <style>
        /* 基础布局样式 */
        .mainBox {
            padding: 20px;
        }

        .main-container {
            max-width: 600px;
            margin: 0 auto;
        }

        .layui-form-item {
            margin-bottom: 25px;
        }

        /* 提示文本样式 */
        .form-tip {
            display: block;
            margin-top: 8px;
            color: #666;
            font-size: 12px;
            line-height: 1.5;
        }

        .form-tip i {
            color: #1E9FFF;
            margin-right: 4px;
        }

        /* 模板信息展示区域 */
        .template-info {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 15px;
            border-left: 4px solid #1E9FFF;
            margin-bottom: 20px;
        }

        .template-info .info-item {
            margin-bottom: 8px;
            display: flex;
        }

        .template-info .info-label {
            font-weight: bold;
            min-width: 80px;
            color: #333;
        }

        .template-info .info-value {
            color: #666;
            flex: 1;
        }

        /* JSON示例容器 */
        .json-example {
            margin-top: 8px;
            padding: 10px;
            background: #f8f8f8;
            border-radius: 4px;
            border: 1px solid #eee;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            color: #333;
            white-space: pre-wrap;
            word-break: break-all;
            line-height: 1.4;
        }

        /* 底部按钮区域 */
        .bottom {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 15px 20px;
            background: #fff;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
            z-index: 99;
            border-top: 1px solid #e8e8e8;
        }

        .button-container {
            text-align: center;
            max-width: 600px;
            margin: 0 auto;
        }

        .button-container button {
            margin: 0 10px;
            min-width: 80px;
        }

        /* 输入框样式 */
        .layui-input,
        .layui-textarea {
            border-radius: 4px;
            border: 1px solid #dcdfe6;
            transition: border-color 0.3s;
        }

        .layui-input:focus,
        .layui-textarea:focus {
            border-color: #1E9FFF;
            box-shadow: 0 0 0 2px rgba(30, 159, 255, 0.1);
        }

        /* 发送状态样式 */
        .send-status {
            text-align: center;
            padding: 20px;
            margin: 20px 0;
            border-radius: 6px;
            display: none;
        }

        .send-status.success {
            background: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #52c41a;
        }

        .send-status.error {
            background: #fff2f0;
            border: 1px solid #ffccc7;
            color: #ff4d4f;
        }
    </style>
</head>

<body>
    <form class="layui-form" action="" lay-filter="send-test-form">
        <div class="mainBox">
            <div class="main-container">
                <!-- 模板信息展示 -->
                <div class="template-info">
                    <div class="info-item">
                        <div class="info-label">模板标题：</div>
                        <div class="info-value" id="template-name">加载中...</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">模板CODE：</div>
                        <div class="info-value" id="template-code">加载中...</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">模板签名：</div>
                        <div class="info-value" id="template-sign">加载中...</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">供应商：</div>
                        <div class="info-value" id="template-provider">加载中...</div>
                    </div>
                </div>

                <!-- 1. 手机号码输入 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">手机号码 <span style="color: #ff4d4f;">*</span></label>
                    <div class="layui-input-block">
                        <input type="text" name="phone" id="phone" lay-verify="required|phone" autocomplete="off"
                            placeholder="请输入接收测试短信的手机号码" class="layui-input" maxlength="11">
                        <span class="form-tip">
                            <i class="layui-icon layui-icon-info"></i>
                            请输入正确的11位手机号码，用于接收测试短信
                        </span>
                    </div>
                </div>

                <!-- 2. 模板变量编辑 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">测试变量</label>
                    <div class="layui-input-block">
                        <textarea name="test_data" id="test_data" lay-verify="verifyJson" autocomplete="off"
                            placeholder="请输入测试用的模板变量（JSON格式）" class="layui-textarea" rows="6"></textarea>
                    </div>
                </div>

                <!-- 发送状态显示 -->
                <div class="send-status" id="send-status">
                    <i class="layui-icon" id="status-icon"></i>
                    <span id="status-text"></span>
                </div>
            </div>
        </div>

        <!-- 底部提交按钮区域 -->
        <div class="bottom">
            <div class="button-container">
                <button type="submit" class="pear-btn pear-btn-success pear-btn-sm" lay-submit
                    lay-filter="send-sms-test">
                    <i class="layui-icon layui-icon-send"></i>
                    发送测试
                </button>
                <button type="button" class="pear-btn pear-btn-primary pear-btn-sm" id="reset-btn">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置
                </button>
                <button type="button" class="pear-btn pear-btn-danger pear-btn-sm" id="close-btn">
                    <i class="layui-icon layui-icon-close"></i>
                    取消
                </button>
            </div>
        </div>
    </form>

    <!-- 引入依赖JS文件 -->
    <script src="../../../component/com/api.js"></script>
    <script src="../../../component/com/auth.js"></script>
    <script src="../../../component/layui/layui.js"></script>
    <script src="../../../component/pear/pear.js"></script>
    <script>
        layui.use(['form', 'jquery', 'layer'], function () {
            let form = layui.form;
            let $ = layui.jquery;
            let layer = layui.layer;

            // 1. 基础配置
            const API_BASE_URL = apiConfig.baseUrl;
            const TOKEN = window.localStorage.getItem("token") || window.sessionStorage.getItem("token");

            // 2. 获取URL参数（模板ID）
            function getUrlParams() {
                let params = {};
                let search = window.location.search.substring(1);
                if (search) {
                    search.split('&').forEach(function (param) {
                        let pair = param.split('=');
                        params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
                    });
                }
                return params;
            }

            const urlParams = getUrlParams();
            const templateId = urlParams.id;
            const SMS_TEMPLATE_DETAIL_API = `${API_BASE_URL}/sms/template/${templateId}/`;

            // 3. 页面初始化：加载模板详情
            $(function () {
                if (!templateId) {
                    layer.msg('模板ID参数缺失', { icon: 2 });
                    return;
                }
                loadTemplateDetail();
            });

            // 4. 加载模板详情
            function loadTemplateDetail() {
                const loading = layer.load(2, { shade: 0.3, shadeClose: false });
                $.ajax({
                    url: SMS_TEMPLATE_DETAIL_API,
                    type: 'GET',
                    headers: { "Authorization": TOKEN },
                    dataType: 'json',
                    success: function (res) {
                        layer.close(loading);
                        if (res.success) {
                            const template = res.data;
                            // 填充模板信息
                            $('#template-name').text(template.name || '未知');
                            $('#template-code').text(template.template_id || '未知');
                            $('#template-sign').text(template.sign || '未知');
                            $('#template-provider').text(template.sms_provider_name || '未知');

                            // 设置默认测试数据
                            if (template.template_data) {
                                try {
                                    const templateData = typeof template.template_data === 'string' ?
                                        JSON.parse(template.template_data) : template.template_data;
                                    $('#test_data').val(JSON.stringify(templateData, null, 2));
                                } catch (e) {
                                    $('#test_data').val('{}');
                                }
                            } else {
                                $('#test_data').val('{}');
                            }
                        } else {
                            layer.msg('加载模板详情失败: ' + (res.message || '未知错误'), { icon: 2, time: 2000 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.close(loading);
                        layer.msg('加载模板详情失败，请检查网络连接', { icon: 2, time: 2000 });
                    }
                });
            }

            // 5. 表单自定义校验规则
            form.verify({
                // 手机号验证
                phone: function (value) {
                    const trimVal = value.trim();
                    if (!trimVal) return "手机号码不能为空";
                    if (!/^1[3-9]\d{9}$/.test(trimVal)) {
                        return "请输入正确的11位手机号码";
                    }
                },
                // JSON格式校验
                verifyJson: function (value) {
                    const trimVal = value.trim();
                    if (!trimVal) return; // 允许为空

                    try {
                        JSON.parse(trimVal);
                    } catch (e) {
                        return "测试变量格式错误，请输入标准JSON格式";
                    }
                }
            });

            // 6. 表单提交事件（发送测试短信）- 修复URL斜杠问题
            form.on('submit(send-sms-test)', function (data) {
                const phone = data.field.phone.trim();
                let testData = {};

                // 解析测试数据
                if (data.field.test_data.trim()) {
                    try {
                        testData = JSON.parse(data.field.test_data.trim());
                    } catch (e) {
                        layer.msg('测试变量JSON格式错误', { icon: 2 });
                        return false;
                    }
                }

                // 显示发送状态
                showSendStatus('sending', '发送中...');

                // 发送测试请求 - 修复URL斜杠问题
                const loading = layer.load(2, { shade: 0.3, shadeClose: false });

                // 关键修复：确保URL以斜杠结尾
                $.ajax({
                    url: `${API_BASE_URL}/sms/template/test/send/${templateId}/`,  // 注意末尾的斜杠
                    type: 'POST',
                    headers: {
                        "Authorization": TOKEN,
                        "Content-Type": "application/json"
                    },
                    data: JSON.stringify({
                        phone: phone,
                        test_data: testData
                    }),
                    dataType: 'json',
                    success: function (result) {
                        layer.close(loading);
                        if (result.success) {
                            showSendStatus('success', result.message || '测试短信发送成功！');
                            // 3秒后自动关闭状态提示
                            setTimeout(() => {
                                $('#send-status').hide();
                            }, 3000);
                        } else {
                            const errorMsg = result.message || "发送失败，请重试";
                            showSendStatus('error', errorMsg);
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.close(loading);
                        let errorMsg = "网络请求异常，请检查接口或网络";
                        if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorMsg = xhr.responseJSON.message;
                        }
                        showSendStatus('error', errorMsg);
                    }
                });

                return false; // 阻止默认提交
            });

            // 7. 显示发送状态
            function showSendStatus(type, message) {
                const statusEl = $('#send-status');
                const iconEl = $('#status-icon');
                const textEl = $('#status-text');

                statusEl.removeClass('success error').show();
                iconEl.removeClass('layui-icon-ok layui-icon-close layui-icon-loading layui-anim layui-anim-rotate');

                switch (type) {
                    case 'sending':
                        statusEl.addClass('success');
                        iconEl.addClass('layui-icon-loading layui-anim layui-anim-rotate');
                        textEl.text(message);
                        break;
                    case 'success':
                        statusEl.addClass('success');
                        iconEl.addClass('layui-icon-ok');
                        textEl.text(message);
                        break;
                    case 'error':
                        statusEl.addClass('error');
                        iconEl.addClass('layui-icon-close');
                        textEl.text(message);
                        break;
                }
            }

            // 8. 取消按钮事件：关闭弹窗
            $('#close-btn').on('click', function () {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });

            // 9. 重置按钮事件
            $('#reset-btn').on('click', function () {
                // 重置表单但保留模板信息
                $('#phone').val('');
                loadTemplateDetail(); // 重新加载默认测试数据
                $('#send-status').hide();
                form.render();
            });

            // 10. 回车键提交表单
            $(document).on('keypress', function (e) {
                if (e.which === 13) {
                    $('button[lay-filter="send-sms-test"]').click();
                }
            });
        });
    </script>
</body>

</html>